<template>
	<view class="mbti-wifi">
		<mBack ref="mBack" @getGameResult="handleBack"></mBack>


		<view class="mbti-wifi-content " :style="{'background-image': `url(${bgUrl})`}">
			<view class="wifi-content" v-if="blueIsLinked">
				<scroll-view ref="scrollView" :scroll-y="true" class="scroll-content" :show-scrollbar="false"
					:scroll-with-animation="true">
					<view class="top-box" :style="{height:contentTop+'rpx'}">
					</view>
					<view class="wifi-top-tip" @click="handleDisCoverDevice">从列表中选择WiFi连接</view>
					<!-- 已保存的网络 -->
					<view class="group-tip" @click="handleTestClick" v-if="savedWiFiList.length">已连接的网络</view>
					<view class="wifi-top-list wifi-list">
						<view class="wifi-item flex-row-start-center" v-for="(item,index) in savedWiFiList"
							:key="index">
							<view class="wifi-icon">
								<image
									src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/61002066a2114305ae19349e6047a43f.png"
									class="cover-img" mode="aspectFill" v-if="item.linked"></image>
								<image
									src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/7c948a4eb3264fb8b82fee40314ad30e.png"
									class="cover-img loading-icon" mode="aspectFill" v-if="item.loading"></image>
							</view>
							<view class="item-info flex-row-start-center">
								<view class="wifi-name flex-row-start-center">{{item.SSID}}</view>
								<view class="wifi-control-icon-list flex-row-end-center">
									<image class="wifi-icon-locked control-icon-base"
										src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/bf687a8fc0aa4dcb991d3b7410b5282d.png"
										mode="aspectFill" v-if="item.secure"></image>
									<image class="wifi-icon-signal control-icon-base" v-if="sinalLevelIcon"
										:src="item.sinalLevelIcon" mode="aspectFill" style="margin-right: -1rpx;">
									</image>
									<image class="control-icon-base wifi-icon-delete"
										src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/963e392ba574491b863e49a7e77b2b0d.png"
										mode="aspectFill" style="margin-right: -6rpx;"></image>
								</view>

							</view>
						</view>
					</view>
					<view class="group-tip">新的网络</view>
					<view class="wifi-bottom-list wifi-list">
						<view class="bottom-wifi-list-content flex-column-start-center">
							<!-- :class="{'hide-wifi':linkWifiName==item.SSID}" -->
							<view class="wifi-item flex-row-start-center" v-for="(item,index) in wifiList" :key="index"
								@click="handleNewWiFiItemClick(item,index)"
								:class="{'hide-wifi':savedNameList.includes(item.SSID)}">
								<view class="wifi-icon">
									<image
										src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/61002066a2114305ae19349e6047a43f.png"
										class="cover-img" mode="aspectFill" v-if="item.linked"></image>
									<image
										src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/7c948a4eb3264fb8b82fee40314ad30e.png"
										class="cover-img loading-icon" mode="aspectFill" v-if="item.loading"></image>
								</view>
								<view class="item-info flex-row-start-center">
									<view class="wifi-name flex-row-start-center">{{item.SSID}}</view>
									<view class="wifi-control-icon-list flex-row-end-center">
										<image class="wifi-icon-locked control-icon-base"
											src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/bf687a8fc0aa4dcb991d3b7410b5282d.png"
											mode="aspectFill" v-if="item.secure"></image>
										<image class="wifi-icon-signal control-icon-base" :src="item.sinalLevelIcon"
											mode="aspectFill" style="margin-right: -1rpx;"></image>
									</view>
								</view>
							</view>

							<view class="wifi-item flex-row-start-center" @click="handleWifiOtherClick">
								<view class="wifi-icon">
								</view>
								<view class="item-info flex-row-start-center">
									<view class="wifi-name flex-row-start-center">其他...</view>
								</view>
							</view>
						</view>






					</view>


				</scroll-view>


			</view>
			<view class="tip-box flex-column-start-center" v-else>
				<view class="top-box" :style="{height:contentTop1+'rpx'}"></view>
				<view class="tip-title">连接你的设备</view>
				<view class="tip-sub-title flex-row-start-center">
					长按电源键 <image class="switch-icon"
						src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/4722c60c92994455b29f6ae05dd3030d.png"
						mode="aspectFill"></image>，重启你的设备
				</view>
				<view class="tip-sub-title" style="margin-bottom: 148rpx;">
					快速按一下主按钮，进入配网模式
				</view>
				<view class="discover-blue-searching flex-column-start-center">
					<view class="discover-blue-icon flex-row-center-center">
						<view class="discover-blue-center flex-row-center-center">
							<view class="discover-blue-center-content flex-row-center-center">
								<image class="discover-blue-center-icon"
									src="https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/23cca55db59043e6b00c9cf6cad0db06.png"
									mode="aspectFill"></image>
							</view>
							<view class="blue-child"></view>
							<view class="blue-child blue-child-two"></view>
							<view class="blue-child blue-child-three"></view>

						</view>
					</view>
					<view class="discover-blue-tip">连接中...</view>
				</view>
			</view>
		</view>


		<mbtiPop ref="mbtiPop" @confirmValue="handleConfirmValue"></mbtiPop>

	</view>
</template>

<script>
	var xBlufi = require("@/utils/blufi/xBlufi.js");


	var _this = null;
	var timeout = null;
	var interval_timer = null;
	var sequenceCounet = 0;
	var newScanListLength = -1;
	var oldScanListLength = 0;

	const SCAN_STEP = 0;
	const INPUT_STEP = 1;
	const DONE_STEP = 2;


	import mbtiPop from "@/components/m-mbti/mbti-pop.vue"
	import mBack from "@/components/m-back/index.vue"
	import {
		mapGetters
	} from "vuex"
	import {
		getNowDeviceInfo
	} from "@/api/mbti.js"
	export default {
		components: {
			mbtiPop,
			mBack
		},
		data() {
			return {
				sys: "ios", //ios android
				bgUrl: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/d394a848c52a40a0b7fc9baf22ba6a01.png",
				screenWidth: 375,
				rpxMenuButtonHeight: 64,
				rpxMenuButtonTop: 100,
				contentTop: 300,
				contentTop1: 300,
				wifiSinalLevelList: [{
						level: 3,
						icon: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/1a811e7e0e334d1fb01c26dc5cf5aaec.png"
					},
					{
						level: 2,
						icon: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/b36c532b1743449c928ebba8fa6850a5.png"
					},
					{
						level: 1,
						icon: "https://cdn.osisx.com/e416845113cdf0df55ad616de9bf72b2/image/c1a2542027444024ae9f3fed2acb66b5.png"
					},
				],
				savedWiFiList: [
					// {
					// 	SSID: "你好宝宝",
					// 	password: "",
					// 	secure: true,
					// 	strength: 3, //1、2、3
					// 	linked: true,
					// 	loading: false

					// },
					// {
					// 	SSID: "凯凯的iphone",
					// 	password: "",
					// 	secure: true,
					// 	strength: 3, //1、2、3
					// 	linked: false,
					// 	loading: true,
					// },
				],
				newWifiList: [{
						SSID: "凯宝宝 不吃香菜",
						password: "",
						secure: false,
						strength: 3, //1、2、3
						linked: false,
						loading: false

					},
					{
						SSID: "XINGZAI_2.4G",
						password: "",
						secure: true,
						strength: 3, //1、2、3
						linked: false,
						loading: false
					},
					{
						SSID: "黑鲨5",
						password: "",
						secure: true,
						strength: 3, //1、2、3
						linked: false,
						loading: false
					},

				],
				wifiList: [],
				refreshIntervalId: null,



				// 蓝牙相关数据
				getWifiFirst: true,
				blufiloadInfo: "扫描设备",
				blufiLoadStatus: false,
				blufiScanStatus: false,
				showPassword: false,
				macFilter: "",
				stepActive: 0,
				ssid: "",
				password: "",
				steps: [{
						text: '1.连接设备'
					},
					{
						text: '2.填写WiFi'
					},
					{
						text: '3.配网成功'
					}
				],
				deviceId: '', //测试时使用
				deviceName: '',
				devicesListTemp: [],
				devicesList: [],


				// mac地址
				deviceMacAddress: null,

				actSSID: null,
				linkWifiName: "",
				isLinkLoading: false,

				waitRestart: false,

				blueIsLinked: false,
				onlineStatus: 0,
				waitRestartInterval: null

			}
		},
		created() {
			try {
				let screenWidth = uni.getStorageSync('screenWidth')
				if (screenWidth) {
					this.screenWidth = screenWidth
				} else {
					this.screenWidth = uni.getSystemInfoSync().screenWidth; // 当前设备屏幕宽度
					uni.setStorageSync("screenWidth", this.screenWidth)
				}
				let menuButtonInfo = uni.getMenuButtonBoundingClientRect()
				let {
					top,
					height
				} = menuButtonInfo

				let rpxHeight = this.pxToRpx(height)
				let rpxTop = this.pxToRpx(top)
				this.rpxMenuButtonHeight = rpxHeight
				this.rpxMenuButtonTop = rpxTop

				this.contentTop = rpxTop + rpxHeight + 72
				this.contentTop1 = rpxTop + rpxHeight + 98

			} catch (error) {
				//TODO handle the exception
			}
		},
		onLoad(options) {
			this.deviceMacAddress = options.macAddress
			_this = this;
			xBlufi.initXBlufi(1);
			xBlufi.listenDeviceMsgEvent(true, this.blufiEventHandler);
			//clear status
			this.blufiIntercalClear()
			xBlufi.notifyStartDiscoverBle({
				'isStart': false
			})
			this.devicesList = []
			this.handleDisCoverDevice()


		},
		onUnload() {
			_this = this
			xBlufi.notifyConnectBle({
				isStart: false,
				deviceId: _this.deviceId,
				name: _this.deviceName,
			});
			xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
			xBlufi.notifyStartDiscoverBle({
				'isStart': false
			})
			this.blufiIntercalClear()
			clearInterval(this.refreshIntervalId)
			this.isLinkLoading = false
			this.waitRestart = false
			wx.stopWifi()

		},
		onShow() {
			this.listenWifiEvents();
		},
		computed: {
			...mapGetters(['systemInfo']),
			savedNameList() {
				let arr = []
				arr = this.savedWiFiList.map((item, index) => {
					return item.SSID
				})
				return arr
			}
		},
		methods: {
			pxToRpx(px) {
				const designWidth = 750; // 设计稿宽度
				const rpx = (designWidth / this.screenWidth) * px; // 根据屏幕宽度计算 rpx
				return rpx;
			},
			handleConfirmValue(e) {
				let {
					data,
					code,
					title,
				} = e

				if (code == "other") {
					let ssid = data[0].value
					let password = data[0].value
					this.actSSID = ssid
					console.log("返回的数据是", ssid, password)
					this.startConfig(ssid, password)
					let obj = {
						SSID: ssid,
						password: password,
						loading: true,
						secure: false,
						sinalLevelIcon: null
					}
					this.savedWiFiList.push(obj)
				} else if (code == "new") {
					let ssid = data[0].ssid
					let password = data[0].value
					this.actSSID = ssid
					console.log("返回的数据是1", ssid, password)

					this.startConfig(ssid, password)
					let obj = this.wifiList.find((item, index) => {
						return item.ssid == ssid
					})
					if (obj) {
						let obj1 = {
							...obj
						}
						obj1.loading = true
						this.savedWiFiList.push(obj1)
						console.log("confirm之后", this.savedWiFiList)
					}

				} else if (code == "old") {

				}
				this.isLinkLoading = true
			},
			handleGetNowDeviceInfo() {
				return new Promise(async (resolve, reject) => {
					resolve()
					// let res = await getNowDeviceInfo()
					// try {
					// 	let data = res.data.data
					// 	if (data) {
					// 		// this.deviceMacAddress = data.macAddress
					// 		// MBTI_806599D00E90
					// 		this.deviceMacAddress = data.macAddress
					// 		this.linkWifiName = data.wifiName
					// 		this.onlineStatus = data.onlineStatus

					// 		resolve(true)
					// 		console.log("数据是", data, this.deviceMacAddress);
					// 	} else {
					// 		uni.showToast({
					// 			title: "设备详情获取失败",
					// 			icon: "none"
					// 		})
					// 		reject()
					// 	}
					// } catch (error) {
					// 	//TODO handle the exception
					// 	uni.showToast({
					// 		title: "设备详情获取失败",
					// 		icon: "none"
					// 	})
					// 	reject()
					// }
				})


			},
			handleBack() {
				uni.navigateBack()
			},
			handleNewWiFiItemClick(item, index) {
				if (this.isLinkLoading) {
					return
				}
				console.log("宝宝", item);
				if (item.secure) {
					this.$refs.mbtiPop.open({
						data: [{
							label: "密码",
							value: "",
							type: "label-in",
							valueType: "password",
							isRequire: true,
							ssid: item.SSID
						}, ],
						title: `输入"${item.SSID}"的密码`,
						code: "new"
					})
				}
			},
			handleWifiOtherClick() {
				this.$refs.mbtiPop.open({
					data: [{
							label: "SSID",
							value: "",
							type: "label-in",
							valueType: "text",
							isRequire: true,
						},
						{
							label: "密码",
							value: "",
							type: "label-in",
							valueType: "password",
							isRequire: true,
						},
					],
					title: "新的WiFi连接",
					code: "other"
				})
			},
			// 
			getWiFiSinalLevel(wifiItem) {
				let platform = this.systemInfo.osName
				let strength = wifiItem.signalStrength;
				// iOS 处理
				if (platform.includes('ios')) {
					if (strength >= 0.7) return 2;
					else if (strength >= 0.4) return 1;
					else return 0;
				}
				// Android 处理（假设 Android 返回 0-100）
				else {
					if (strength > 80) return 2;
					else if (strength > 40) return 1;
					else return 0;
				}
			},
			handleTestClick() {
				// console.log("刷新");
				this.scanWifi()
				// wx.openBluetoothAdapter({
				// 	success: (res) => {
				// 		wx.createBLEConnection({
				// 			deviceId: "D9CDE327-42BA-D375-AF04-E86BBE4A1893",
				// 			success() {
				// 				console.log("连接成功");
				// 			},
				// 			fail() {
				// 				console.log("连接失败");
				// 			}
				// 		})
				// 	},
				// 	fail: (err) => {}
				// })
			},
			// 初始化模块
			async initWifi1() {
				console.log("初始化调用");
				this.startWifi().then(res => {
					console.log("成功", res);
					uni.showLoading({
						title: "获取wifi列表~",
						icon: "none"
					})
					this.scanWifi()
					// this.handleAutoRefreshWifiList()
				}).catch(err => {
					console.log('失败', err);
				})
			},
			// 启动WiFi模块
			startWifi() {

				return new Promise((resolve, reject) => {
					uni.startWifi({
						success: resolve,
						fail: reject
					});
				});
			},
			handleAutoRefreshWifiList() {
				this.refreshIntervalId = setInterval(() => {
					this.scanWifi()
				}, 2000)
			},

			handleGetLevelIon(level) {
				let obj = this.wifiSinalLevelList.find((item, index) => {
					return item.level == level
				})

				return obj ? obj.icon : ""

			},

			// 监听事件
			listenWifiEvents() {
				console.log("监听调用");
				wx.onGetWifiList(res => {
					const wifiMap = {}; // 用 SSID 作为 key，存储信号最强的 WiFi 对象
					res.wifiList.forEach((wifi) => {
						const currentSSID = wifi.SSID;
						const currentStrength = wifi.signalStrength;
						// 如果当前 SSID 未记录，或新信号更强：直接覆盖旧值
						if (
							!wifiMap[currentSSID] ||
							currentStrength > wifiMap[currentSSID].signalStrength
						) {
							wifiMap[currentSSID] = {
								...wifi
							}; // 完全覆盖为新的 WiFi 对象
						}
					});

					// 转换为去重后的数组（每个 SSID 仅保留信号最强的完整信息）
					const uniqueWifiList = Object.values(wifiMap);
					let arr = uniqueWifiList.map((item, index) => {
						let sinalLevel = this.getWiFiSinalLevel(item)
						let sinalLevelIcon = this.handleGetLevelIon(sinalLevel)
						return {
							...item,
							sinalLevel,
							sinalLevelIcon

						}
					})
					if (arr.length && this.getWifiFirst) {
						this.getWifiFirst = false
						uni.hideLoading()
						uni.showToast({
							title: "wifi列表已获取~",
							icon: "none"
						})
					}

					this.wifiList = [...arr]
					// let obj = this.wifiList.find((item, index) => {
					// 	return item.SSID == this.linkWifiName
					// })
					// if (obj && !this.savedWiFiList.length) {
					// 	let obj1 = {
					// 		...obj
					// 	}
					// 	obj1.linked = true
					// 	this.savedWiFiList.push(obj1)
					// }


				})
			},
			// 触发扫描
			scanWifi() {
				console.log("调用")
				return new Promise((resolve, reject) => {
					uni.getWifiList({
						success(res) {
							console.log("开启扫描成功", res);
							resolve(res)
						},
						fail(err) {
							console.log("开启扫描失败");
							reject(err)
						}
					});
				})
			},


			// 自定义
			handleDisCoverDevice() {
				this.setValue("blufiScanStatus", !this.blufiScanStatus)
				if (this.blufiScanStatus) {
					// uni.showLoading({
					// 	title: "扫描设备中~",
					// 	icon: "none"
					// })
					xBlufi.notifyStartDiscoverBle({
						'isStart': true
					})
					console.log("start scan!")
					this.setValue("blufiloadInfo", "扫描中")
					this.setValue("blufiLoadStatus", true)
					interval_timer = setInterval(() => {
						this.blufiUpdateList();
					}, 900);
				} else {
					this.blufiIntercalClear()
					console.log("stop scan!")
					xBlufi.notifyStartDiscoverBle({
						'isStart': false
					})
					this.setValue("blufiloadInfo", "开始扫描")
					this.setValue("blufiLoadStatus", false)
				}
			},
			// 来自迁移
			setValue(key, value) {
				// this.setData({
				// 	[key]: value,
				// });
				this[key] = value
			},
			onClickeye() {
				this.setValue("showPassword", !this.showPassword)
			},
			blufiBtnHandle() {
				wx.vibrateShort()
				let status = this.stepActive
				switch (status) {
					case SCAN_STEP:
						this.setValue("blufiScanStatus", !this.blufiScanStatus)
						if (this.blufiScanStatus) {
							xBlufi.notifyStartDiscoverBle({
								'isStart': true
							})
							console.log("start scan!")
							this.setValue("blufiloadInfo", "扫描中")
							this.setValue("blufiLoadStatus", true)
							interval_timer = setInterval(() => {
								this.blufiUpdateList();
							}, 900);
						} else {
							this.blufiIntercalClear()
							console.log("stop scan!")
							xBlufi.notifyStartDiscoverBle({
								'isStart': false
							})
							this.setValue("blufiloadInfo", "开始扫描")
							this.setValue("blufiLoadStatus", false)
						}
						break;
					case INPUT_STEP:
						this.startConfig()
					case DONE_STEP:
						break;
					default:
						break;
				}
			},
			blufiConnect(e) {
				this.setValue("blufiloadInfo", "连接中")
				if (interval_timer) {
					clearInterval(interval_timer)
				}
				//停止搜索
				xBlufi.notifyStartDiscoverBle({
					'isStart': false
				})
				xBlufi.notifyConnectBle({
					isStart: true,
					deviceId: this.deviceId,
					name: this.deviceName
				});
				// wx.showLoading({
				// 	title: '连接蓝牙设备中...',
				// })
				timeout = setTimeout(() => {
					this.blufiTimeoutHandle()
				}, 10000)
			},
			blufiEventHandler: function(options) {
				switch (options.type) {
					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS: //设备列表获取到了
						if (options.result) {
							_this.devicesListTemp = [...options.data].filter((item, index) => {
								return (String(item.name).includes("MBTI"))
							})
							console.log("获取到的设备列表是", _this.devicesListTemp)
						}
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_CONNECTED: //蓝牙连接回调
						console.log("连接回调：" + JSON.stringify(options))
						if (options.result) {
							wx.hideLoading()
							sequenceCounet = 0;
							setTimeout(() => {
								wx.showToast({
									title: '设备连接成功~',
									icon: 'none'
								})
								this.blueIsLinked = true
							}, 200)

							this.blufiTimeoutClear()
							this.stepActive = 1
							this.blufiLoadStatus = false
							xBlufi.notifyInitBleEsp32({
								deviceId: this.deviceId,
							})

							setTimeout(() => {
								uni.showLoading({
									title: "扫描WIFI列表~",
									icon: "none"
								})
							}, 1000)

						}
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_START: //开始获取设备列表
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_GET_DEVICE_LISTS_STOP: //蓝牙停止搜索
						if (options.result) {
							//蓝牙停止搜索ok
							console.log('蓝牙停止搜索ok')
							this.blufiLoadStatus = false
							this.blufiScanStatus = false

						} else {
							//蓝牙停止搜索失败
							console.log('蓝牙停止搜索失败')
						}
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_STATUS_CONNECTED: //设备连接状态回调
						console.log('设别连接状态回调', options)
						if (!options.connected) {
							// uni.showToast({
							// 	title: "设备连接失败~",
							// 	icon: "none"
							// })
							if (this.waitRestart == true) {
								this.waitRestart = false
								// setTimeout(() => {
								// 	uni.hideLoading()
								// 	uni.navigateBack()
								// }, 3000)

								this.waitRestartInterval = setInterval(() => {
									// 不需要
									// if (this.onlineStatus == 1) {
									// 	clearInterval(this.waitRestartInterval)
									// 	uni.hideLoading()
									// 	uni.navigateBack()
									// } else {
									// 	this.handleGetNowDeviceInfo()
									// }
								}, 1000)

							} else {
								// uni.hideLoading()
							}
						} else {
							console.log("蓝牙连接成功！")
						}
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_CONNECT_ROUTER_RESULT: //配网结果
						wx.hideLoading();
						return
						if (!options.result) {
							sequenceCounet = 0;
							// wx.showModal({
							// 	title: '温馨提示',
							// 	content: '配网失败，请重试',
							// 	showCancel: false, //是否显示取消按钮
							// })
							uni.showToast({
								title: "配网失败，请重试~",
								icon: "none"
							})

							let sindex = null
							this.savedWiFiList.forEach((item, index) => {
								if (item.SSID == this.actSSID) {
									sindex = index
								}
							})
							if (sindex !== null) {
								this.savedWiFiList.splice(sindex, 1)
							}
							this.actSSID = null
							this.isLinkLoading = false
							// this.blufiReset()
						} else {
							console.log("配网结果", options);
							if (options.data.progress == 100) {
								uni.showToast({
									title: "配网成功~",
									icon: "none",
									duration: 3000
								})
								// this.savedWiFiList.forEach((item, index) => {
								// })
								console.log("配网成功处理前", this.savedWiFiList)
								let sindex = null
								this.savedWiFiList.forEach((item, index) => {
									if (item.ssid == this.actSSID) {
										item.linked = true
										item.loading = false
									} else {
										sindex = index
										item.linked = false
									}
								})
								console.log("配网成功处理后", this.savedWiFiList)
								console.log("应该被删除的是", sindex)
								console.log("保留的对象是", obj);
								if (sindex !== null) {
									this.savedWiFiList.splice(sindex, 1)
									this.linkWifiName = this.actSSID
								}
								this.actSSID = null
								this.blufiTimeoutClear()
								this.isLinkLoading = false

								// 关闭掉所有的东西
								setTimeout(() => {
									this.handleAllClose()
								}, 3000)
								// uni.navigateBack()
								// uni.showLoading({
								// 	title: "等待设备重启~",
								// 	icon: "none"
								// })





								// this.waitRestart = true




							}
						}
						break;
					case xBlufi.XBLUFI_TYPE.TYPE_RECIEVE_CUSTON_DATA:
						// wx.showModal({
						// 	title: '收到自定义设备数据',
						// 	content: `【${options.data}】`,
						// 	showCancel: false, //是否显示取消按钮
						// })
						let arr = []
						let data = null
						try {
							const sanitized = String(options.data).replace(/[\u0000-\u001F]/g, '');
							data = JSON.parse(sanitized);
							console.log("拿到的数据是", data)
							if (data.ssids) {
								arr = data.ssids.map((item, index) => {
									let sinalLevelIcon = this.handleGetLevelIon(item.class)
									let obj = {
										...item,
										SSID: item.ssid,
										sinalLevelIcon,
										secure: true
									}
									return obj
								})
							}

						} catch (error) {}
						if (data.ssids) {
							if (arr.length && this.getWifiFirst) {
								this.getWifiFirst = false
								uni.hideLoading()
								uni.showToast({
									title: "wifi列表已获取~",
									icon: "none"
								})
							}

							this.wifiList = [...arr]
							// let obj = this.wifiList.find((item, index) => {
							// 	return item.SSID == this.linkWifiName
							// })
							// if (obj && !this.savedWiFiList.length) {
							// 	let obj1 = {
							// 		...obj
							// 	}
							// 	obj1.linked = true
							// 	this.savedWiFiList.push(obj1)
							// }
							console.log("解析出来的wifi列表是", arr)

						} else if (data.status) {
							wx.hideLoading();
							let status = data.status
							if (status == 'success') {
								// 配网成功
								uni.showToast({
									title: "配网成功~",
									icon: "none",
									duration: 3000
								})
								// this.savedWiFiList.forEach((item, index) => {
								// })
								console.log("配网成功处理前", this.savedWiFiList)
								// 				let sindex = null
								// 				this.savedWiFiList.forEach((item, index) => {
								// 					if (item.ssid == this.actSSID) {
								// 						item.linked = true
								// 						item.loading = false
								// 					} else {
								// 						sindex = index
								// 						item.linked = false
								// 					}
								// 				})

								// 				if (sindex !== null) {
								// 					this.savedWiFiList.splice(sindex, 1)
								// 					this.linkWifiName = this.actSSID
								// 				}


								this.savedWiFiList.unshift()
								if (this.savedWiFiList[0]) {
									this.savedWiFiList[0].linked = true
									this.savedWiFiList[0].loading = false
								}
								this.actSSID = null
								this.blufiTimeoutClear()
								this.isLinkLoading = false
								setTimeout(() => {
									this.handleAllClose()
								}, 3000)


								// uni.showLoading({
								// 	title: "等待设备重启~",
								// 	icon: "none"
								// })
								// this.waitRestart = true
							} else {
								// 配网失败
								sequenceCounet = 0;
								// wx.showModal({
								// 	title: '温馨提示',
								// 	content: '配网失败，请重试',
								// 	showCancel: false, //是否显示取消按钮
								// })
								uni.showToast({
									title: "配网失败，请重试~",
									icon: "none"
								})

								this.savedWiFiList = []

								this.actSSID = null
								this.isLinkLoading = false
							}
						}

						break;
					case xBlufi.XBLUFI_TYPE.TYPE_INIT_ESP32_RESULT:
						wx.hideLoading();
						console.log("初始化结果：", JSON.stringify(options))
						if (options.result) {
							console.log('初始化成功')

						} else {
							console.log('初始化失败')
							this.connected = false
							// wx.showModal({
							// 	title: '温馨提示',
							// 	content: `设备初始化失败`,
							// 	showCancel: false, //是否显示取消按钮
							// 	success: function(res) {

							// 	}
							// })
						}
						break;
				}
			},
			handleAllClose() {
				_this = this
				xBlufi.notifyConnectBle({
					isStart: false,
					deviceId: _this.deviceId,
					name: _this.deviceName,
				});
				xBlufi.listenDeviceMsgEvent(false, this.funListenDeviceMsgEvent);
				xBlufi.notifyStartDiscoverBle({
					'isStart': false
				})
				this.blufiIntercalClear()
				clearInterval(this.refreshIntervalId)
				this.isLinkLoading = false
				this.waitRestart = false
				this.getWifiFirst = true
				this.wifiList = []
				this.blueIsLinked = false
				wx.stopWifi()
				uni.navigateBack()
			},
			blufiReset: function() {
				wx.closeBLEConnection({
					deviceId: this.deviceId,
					success: function(res) {},
				})
				// this.setValue("blufiloadInfo", "扫描设备")
				this.blufiLoadStatus = false
				this.stepActive = 0
				this.devicesList = []
				// this.deviceId = ""
				this.macFilter = ""

			},
			formatString(str) {
				// 提取下划线后的部分，并立即转小写
				const afterUnderscore = (str.split('_').pop() || '').toLowerCase();

				// 每两位分割并插入冒号
				return afterUnderscore.match(/.{2}/g)?.join(':') || '';
			},
			blufiUpdateList: function() {
				let list = this.devicesListTemp
				var listLen = list.length;
				for (var i = 0; i < listLen - 1; i++) {
					for (var j = 0; j < listLen - 1 - i; j++) {
						if (list[j].RSSI < list[j + 1].RSSI) { // 相邻元素两两对比
							var temp = list[j + 1]; // 元素交换
							list[j + 1] = list[j];
							list[j] = temp;
						}
					}
				}

				list.forEach((item, index) => {
					item.macStr = this.formatString(item.localName)
				})
				console.log("设备列表", list)


				let obj = list.find((item, index) => {
					return item.macStr === this.deviceMacAddress
				})
				console.log("找到的设备是", obj)
				if (obj) {
					uni.hideLoading()
					this.deviceId = obj.deviceId
					this.deviceName = obj.name
					this.blufiIntercalClear()
					// 能找到，直接连接
					this.blufiConnect()
				}


				return
				this.devicesList = list
			},
			blufiTimeoutHandle: function() {
				wx.hideLoading()
				wx.showToast({
					title: '配网超时~',
					icon: 'none'
				})
				// this.blufiReset()
				timeout = null;
				uni.hideLoading()
				sequenceCounet = 0
			},
			blufiTimeoutClear: function() {
				if (timeout) {
					clearTimeout(timeout)
				}
			},
			blufiIntercalClear: function() {
				if (interval_timer) {
					clearInterval(interval_timer)
				}
			},
			encodeUtf8: function(text) {
				const code = encodeURIComponent(text);
				const bytes = [];
				for (var i = 0; i < code.length; i++) {
					const c = code.charAt(i);
					if (c === '%') {
						const hex = code.charAt(i + 1) + code.charAt(i + 2);
						const hexVal = parseInt(hex, 16);
						bytes.push(hexVal);
						i += 2;
					} else bytes.push(c.charCodeAt(0));
				}
				return bytes;
			},
			// 去掉
			initWifi() {
				return
				wx.startWifi();
				wx.getConnectedWifi({
					success: function(res) {
						if (res.wifi.SSID.indexOf("5G") != -1) {
							wx.showToast({
								title: '不支持配置5G WiFi网络',
								icon: 'none',
								duration: 3000
							})
						}
						let password = wx.getStorageSync(res.wifi.SSID)
						console.log("restore password:", password)


						_this.ssid = res.wifi.SSID
						_this.password = password == undefined ? "" : password
					},
					fail: function(res) {
						console.log(res);

						_this.ssid = null
					}
				});
			},
			writeCharacteristicValue: function(data) {
				wx.writeBLECharacteristicValue({
					deviceId: this.deviceId,
					serviceId: "0000FFFF-0000-1000-8000-00805F9B34FB",
					characteristicId: "0000FF01-0000-1000-8000-00805F9B34FB",
					value: data,
					success: function(res) {},
					fail: function(res) {}
				});
			},
			getSequence() {
				sequenceCounet = sequenceCounet > 255 ? 0 : sequenceCounet;
				return sequenceCounet++;
			},
			startConfig(ssid, password) {
				sequenceCounet = 0;
				if (!ssid) {
					wx.showToast({
						title: 'SSID不能为空',
						icon: 'none'
					});
					return;
				}
				if (!password) {
					wx.showToast({
						title: '密码不能为空',
						icon: 'none'
					});
					return;
				}
				uni.showLoading({
					title: '正在配网~',
					icon: "none"
				})
				// wx.showLoading({
				// 	title: '正在配网',
				// 	mask: true
				// });
				this.setValue("blufiloadInfo", "配网中")
				this.setValue("blufiLoadStatus", true)

				let ssid_payload = [0x09, 0x00, this.getSequence()];
				let pwd_payload = [0x0D, 0x00, this.getSequence()];
				let connect_payload = [0x0C, 0x00, 0x02, this.getSequence()];

				var temp_ssid_payload = []
				for (var i = 0; i < ssid.length; i++) {
					var ssid_utf8 = this.encodeUtf8(ssid[i])
					console.log(ssid_utf8)
					temp_ssid_payload.push(...ssid_utf8);
				}

				ssid_payload.push(temp_ssid_payload.length);
				ssid_payload.push(...temp_ssid_payload);
				var temp_pwd_payload = []
				for (var i = 0; i < password.length; i++) {
					var pwd_utf8 = this.encodeUtf8(password[i])
					console.log(pwd_utf8)
					temp_pwd_payload.push(...pwd_utf8);
				}
				pwd_payload.push(temp_pwd_payload.length);
				pwd_payload.push(...temp_pwd_payload);


				var ssidArray = new Uint8Array(ssid_payload);
				var passwordArray = new Uint8Array(pwd_payload);
				var connectCMD = new Uint8Array(connect_payload);

				this.writeCharacteristicValue(ssidArray.buffer)
				this.writeCharacteristicValue(passwordArray.buffer)
				this.writeCharacteristicValue(connectCMD.buffer)

				timeout = setTimeout(() => {
					this.blufiTimeoutHandle()
				}, 300000)
			},


		}
	}
</script>

<style lang="scss" scoped>
	.mbti-wifi {
		position: absolute;
		left: 0rpx;
		top: 0rpx;
		width: 100%;
		height: 100%;
		background-color: #ededed;
		box-sizing: border-box;

		.mbti-wifi-content {
			width: 100%;
			height: 100%;
			background-repeat: no-repeat;
			background-size: cover;
			background-position: center center;

			.tip-box {
				width: 100%;
				height: 100%;

				.tip-title {
					width: 100%;
					height: 56rpx;
					font-weight: 500;
					font-size: 40rpx;
					color: #153135;
					line-height: 56rpx;
					padding: 0 48rpx;
					margin-bottom: 44rpx;
				}

				.tip-sub-title {
					width: 100%;
					height: 44rpx;
					font-weight: 300;
					font-size: 32rpx;
					color: #494949;
					line-height: 44rpx;
					padding: 0 48rpx;
					margin-bottom: 16rpx;

					.switch-icon {
						width: 36rpx;
						height: 36rpx;
						margin-left: 4rpx;
					}

				}

				.discover-blue-searching {
					width: 100%;
					height: 356rpx;
					margin-bottom: 128rpx;

					.discover-blue-icon {
						width: 268rpx;
						height: 268rpx;
						margin-bottom: 44rpx;

						.discover-blue-center {
							position: relative;
							width: 132rpx;
							height: 132rpx;

							.discover-blue-center-content {
								position: absolute;
								left: 50%;
								top: 50%;
								transform: translate(-50%, -50%);
								width: 132rpx;
								height: 132rpx;
								border-radius: 50%;
								background: #99C26D;
								z-index: 9;

								.discover-blue-center-icon {
									width: 40rpx;
									height: 48rpx;
								}
							}


							.blue-child {
								position: absolute;
								left: 50%;
								top: 50%;
								width: 100%;
								height: 100%;
								background: #99C26D;
								border-radius: 50%;
								opacity: 0;
								transform: translate(-50%, -50%);
								animation: searching 3s linear infinite;
								z-index: 1;

							}

							.blue-child-two {
								z-index: 2;
								animation-delay: 1s;
							}

							.blue-child-three {
								z-index: 3;
								animation-delay: 2s;
							}
						}
					}

					@keyframes searching {
						0% {
							transform: translate(-50%, -50%) scale(1);
							opacity: 0.2;
						}

						100% {
							transform: translate(-50%, -50%) scale(3);
							opacity: 0;
						}
					}

					.discover-blue-tip {
						width: 100%;
						height: 44rpx;
						font-weight: 300;
						font-size: 32rpx;
						color: #979797;
						line-height: 44rpx;
						text-align: center;
					}
				}

			}

			.wifi-content {
				width: 100%;
				height: 100%;
				padding: 0rpx 48rpx;
			}


			.wifi-top-tip {
				width: 100%;
				font-weight: 500;
				font-size: 38rpx;
				color: #153135;
				line-height: 52rpx;
				margin-bottom: 64rpx;

			}

			.group-tip {
				width: 100%;
				font-weight: 400;
				font-size: 28rpx;
				color: #494949;
				line-height: 40rpx;
				margin-bottom: 24rpx;
			}

			.wifi-list {
				width: 100%;
				// border-radius: 20rpx;
				// margin-bottom: 52rpx;

				.wifi-item {
					width: 100%;
					height: 104rpx;

					.wifi-icon {
						width: 40rpx;
						height: 40rpx;
						margin-right: 20rpx;

					}

					.wifi-control-icon-list {

						.wifi-icon-locked {}

						.wifi-icon-signal {}


						.control-icon-base {
							width: 32rpx;
							height: 32rpx;
							margin-right: 13rpx;
						}

					}

					.loading-icon {
						animation: rotateLoading 2s linear infinite;

						@keyframes rotateLoading {
							0% {
								transform: rotate(0deg);
							}

							100% {
								transform: rotate(360deg);
							}
						}
					}

					.item-info {
						position: relative;
						flex: 1;
						height: 100%;

						&::after {
							content: "";
							position: absolute;
							left: 0rpx;
							bottom: 0rpx;
							width: 100%;
							height: 0.5rpx;
							background-color: #ebebeb;
						}

						.wifi-name {
							flex: 1;
							height: 100%;
							font-weight: 400;
							font-size: 32rpx;
							color: #494949;
							line-height: 44rpx;
							text-align: left;
						}

						.wifi-icon {}
					}

					&:last-child {
						.item-info {
							&::after {
								display: none;
							}
						}
					}
				}

				.hide-wifi {
					display: none;
				}
			}

			.wifi-top-list {
				padding: 0rpx 28rpx;
				background-color: #fff;
				border-radius: 20rpx;
				margin-bottom: 52rpx;
			}

			.wifi-bottom-list {
				flex: 1;
				overflow: hidden;
			}

			.bottom-wifi-list-content {
				width: 100%;
				background-color: #fff;
				padding: 0rpx 28rpx;
				border-radius: 20rpx;

			}
		}


	}

	.top-box {
		width: 100%;
	}
</style>